package com.cwh.taskcenter.task.executor.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.fastjson.JSON;
import com.cwh.taskcenter.domain.notice.gateway.TaskNotificationGateWay;
import com.cwh.taskcenter.domain.notice.model.TaskNotification;
import com.cwh.taskcenter.domain.task.gateway.TaskRuleGateWay;
import com.cwh.taskcenter.domain.task.model.Task;
import com.cwh.taskcenter.domain.task.gateway.TaskGateWay;
import com.cwh.taskcenter.domain.task.model.TaskRule;
import com.cwh.taskcenter.domain.task.model.TaskStatus;
import com.cwh.taskcenter.notice.converter.TaskNotificationConvert;
import com.cwh.taskcenter.notice.dto.TaskNotificationDTO;
import com.cwh.taskcenter.task.TaskAddCmd;
import com.cwh.taskcenter.task.converter.TaskConvert;
import com.cwh.taskcenter.task.dto.data.TaskDTO;
import com.cwh.taskcenter.task.dto.data.TaskInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cwh
 */
@Slf4j
@Component
public class TaskAddCmdExe {

   @Autowired
   private TaskGateWay taskGateWay;

   @Autowired
   private TaskRuleGateWay taskRuleGateWay;

   @Autowired
   private TaskNotificationGateWay taskNotificationGateWay;


   @Transactional(rollbackFor = Exception.class)
    public Response execute(TaskAddCmd cmd) {

       TaskDTO taskDTO = cmd.getTaskDTO();
       log.info("任务添加:{}", JSON.toJSONString(taskDTO));

        // 1. 领域模型转换
       TaskInfoDTO taskInfo = taskDTO.getTaskInfo();
       Task task = TaskConvert.INSTANCE.toTask(taskInfo);
       task.setTaskStatus(TaskStatus.PUBLISHED);

       List<TaskRule> taskRuleList = taskDTO.getTaskRule().stream().map(t ->{
           TaskRule taskRule = TaskConvert.INSTANCE.toTaskRule(t);
           taskRule.validate();
           return taskRule;
       }).collect(Collectors.toList());

       task.setTaskRules(taskRuleList);
        // 3.保存任务
       Long taskId = taskGateWay.save(task);

       // 4.保存任务规则
       taskRuleGateWay.saveBatch(taskId,taskRuleList);

       // 5.保存通知规则
       TaskNotificationDTO taskNotificationDTO = taskDTO.getTaskNotification();
       TaskNotification taskNotification = TaskNotificationConvert.INSTANCE.toTaskNotificationDTO(taskNotificationDTO);
       taskNotification.setTaskId(taskId);
       taskNotificationGateWay.save(taskNotification);

       // 4. 返回结果
        return Response.buildSuccess();
    }

}
